﻿using SIG.Infrastructure;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.WeiXin.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml.Linq;

namespace SIG.WeiXin
{
   public sealed class WXHelper
    {
        //验证服务器地址的有效性
        public static bool CheckSignature(string signature, string timestamp, string nonce)
        {
            string token = SettingsManager.WeiXin.Token;

            string[] tmpArr = { token, timestamp, nonce };
            Array.Sort(tmpArr);     //字典排序

            string tmpStr = string.Join("", tmpArr); 
            tmpStr = Encryption.GetSwcSHA1(tmpStr);
            tmpStr = tmpStr.ToLower();

            if (tmpStr == signature)
            {
                return true;
            }
            
            return false;
            
        }

        
        //获取签名
        public static void GetAccessToken()
        {
            string URI = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={SettingsManager.WeiXin.AppId}&secret={SettingsManager.WeiXin.AppSecret}";

            using (WebClient wc = new WebClient())
            {
                var json = wc.DownloadString(URI);
                AccessTokenVM AT = Json.JsonDeserialize<AccessTokenVM>(json);

                try
                {
                    var xmlFile = HttpContext.Current.Server.MapPath("~/Config/WeiXinSettings.config");
                    XDocument doc = XDocument.Load(xmlFile);

                    var item = doc.Descendants("Settings").FirstOrDefault();
                    item.Element("AccessToken").SetValue(AT.access_token);
                    item.Element("ExpiresIn").SetValue(AT.expires_in);                  
                    doc.Save(xmlFile);                    
                }
                catch (Exception ex)
                {

                    throw ex;
                }
            }

          
            //var httpClient = new HttpClient();
            //var content = await httpClient.GetStringAsync(URI);
            //return await Task.Run(() => Json.JsonDeserialize<AccessTokenVM>(content));
        }

        #region JS-SDK
        //获取jsapi_ticket
        public static void GetJsapiTicket()
        {
            string URI = $"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={SettingsManager.WeiXin.AccessToken}&type=jsapi";

            using (WebClient wc = new WebClient())
            {
                var json = wc.DownloadString(URI);
                JsapiTicketVM JTVM = Json.JsonDeserialize<JsapiTicketVM>(json);

                try
                {
                    var xmlFile = HttpContext.Current.Server.MapPath("~/Config/WeiXinSettings.config");
                    XDocument doc = XDocument.Load(xmlFile);

                    var item = doc.Descendants("Settings").FirstOrDefault();
                    item.Element("JsapiTicket").SetValue(JTVM.ticket);
                    item.Element("TicketExpiresIn").SetValue(JTVM.expires_in);
                    doc.Save(xmlFile);
                }
                catch (Exception ex)
                {

                    throw ex;
                }
            }
                   
        }

        #endregion
    }



}



